package com.sun.personal.juc;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author syh
 * @date 2021/7/6 13:54
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);  //现在有三个车位，六个人来抢

        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + "\t抢到了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    TimeUnit.SECONDS.sleep(4);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "\t离开了车位");
                semaphore.release();
            },String.valueOf(i)).start();
        }
    }
}

